package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.entity.User;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by 沐风 on 2024/4/25 11:56
 */
@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        //调用通用方法获得日期列表
        List<LocalDate> list = getDateList(begin, end);

        String datelist = StringUtils.join(list, ",");

        //统计每天的已完成订单的金额
        List<Double> list1 = new ArrayList<>();
        for (LocalDate localDate : list) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);

            Double turnover = orderMapper.countTurnover(Orders.COMPLETED,beginTime,endTime);
            //防止是空数据，转为 0.0元
            turnover = turnover == null ? 0.0 : turnover;
            list1.add(turnover);//添加日期对应的营业额
        }

        String turnoverList = StringUtils.join(list1, ",");

        return TurnoverReportVO.builder()
                .dateList(datelist)
                .turnoverList(turnoverList)
                .build();
    }

    /**
     * 用户统计接口
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        //调用通用方法获得日期列表
        List<LocalDate> list = getDateList(begin, end);

        //存放新增用户
        List<Integer> list1 = new ArrayList<>();
        //存放所有用户
        List<Integer> list2 = new ArrayList<>();
        for (LocalDate localDate : list) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);

            Map map = new HashMap<>();
            //统计所有用户
            map.put("end",endTime);
            Integer allUser  = userMapper.countUser(map);
            allUser = allUser == null ? 0 : allUser;
            list2.add(allUser);
            //统计新增用户
            map.put("begin",beginTime);
            Integer newUser  = userMapper.countUser(map);
            newUser = newUser == null ? 0 : newUser;
            list1.add(newUser);

        }

        String datelist = StringUtils.join(list, ",");
        String newUserList = StringUtils.join(list1, ",");
        String totalUserList = StringUtils.join(list2, ",");

        return UserReportVO.builder()
                .dateList(datelist)
                .newUserList(newUserList)
                .totalUserList(totalUserList)
                .build();
    }

    /**
     * 订单统计接口
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO orderStatistics(LocalDate begin, LocalDate end) {
        //调用通用方法获得日期列表
        List<LocalDate> dateLists = getDateList(begin, end);

        List<Integer> ordersList = new ArrayList<>();//存放订单列表
        List<Integer> validOrdersList = new ArrayList<>();//存放有效订单列表
        Integer allOrders = null;//订单总量
        Integer allValidOrder = null;//有效订单总量

        for (LocalDate dateList : dateLists) {
            LocalDateTime beginTime = LocalDateTime.of(dateList, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(dateList, LocalTime.MAX);
            Map map = new HashMap<>();

            //获得订单总量
            map.put("end",endTime);
            allOrders = orderMapper.countOrder(map);
            allOrders = allOrders == null ? 0 : allOrders;

            //获得有效订单总量
            map.put("status",Orders.COMPLETED);
            allValidOrder = orderMapper.countOrder(map);
            allValidOrder = allValidOrder == null ? 0 : allValidOrder;

            //获得订单列表
            map.remove("status");//先把订单状态移除，不然统计的是有效的订单列表
            map.put("begin",beginTime);
            Integer order = orderMapper.countOrder(map);
            order = order == null ? 0 : order;

            ordersList.add(order);

            //获得有效订单列表
            map.put("status",Orders.COMPLETED);
            Integer validOrder = orderMapper.countOrder(map);
            validOrder = validOrder == null ? 0 : validOrder;
            validOrdersList.add(validOrder);
        }

        //计算订单完成率
        Double orderCompletionRate = null;
        if (allOrders == 0){
            orderCompletionRate = 0.0;
        }else {
            orderCompletionRate =  allValidOrder * 1.0 / allOrders;
        }

        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateLists,","))
                .totalOrderCount(allOrders)
                .validOrderCount(allValidOrder)
                .orderCountList(StringUtils.join(validOrdersList,","))
                .validOrderCountList(StringUtils.join(validOrdersList,","))
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 销量top10统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO SalesTop10Statistics(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.getSaleTop10(beginTime,endTime);
        //把上面集合里的数据一个一个拿出来封装到新集合
        List<String> names = goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String nameList = StringUtils.join(names, ",");

        List<Integer> numbers = goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String numberList = StringUtils.join(numbers, ",");

        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    /**
     * 导出数据报表
     * @param response
     */
    @Override
    public void export(HttpServletResponse response) {
        //先获取最近30天的概览数据
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);//为什么截止到昨天，不包含今天呢？因为今天的数据还没统计完
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));

        //通过POI将数据写入到excel文件中
        InputStream is = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            //基于模版文件创建一个新的excel文件
            XSSFWorkbook excel = new XSSFWorkbook(is);

            //填充时间数据
            XSSFSheet sheet = excel.getSheet("sheet1");
            sheet.getRow(1).getCell(1).setCellValue(begin + "至" + end);

            //填充概览数据
            sheet.getRow(3).getCell(2).setCellValue(businessData.getTurnover());
            sheet.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());
            sheet.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());
            sheet.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());
            sheet.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());

            //填充明细数据
            for (int i = 0; i < 30; i++) {
                //每天
                LocalDate date = begin.plusDays(i);
                //获取当天数据
                BusinessDataVO data = workspaceService.getBusinessData(LocalDateTime.of(date,LocalTime.MIN), LocalDateTime.of(date,LocalTime.MAX));

                //填充明细数据
                sheet.getRow(7+i).getCell(1).setCellValue(date.toString());
                sheet.getRow(7+i).getCell(2).setCellValue(data.getTurnover());
                sheet.getRow(7+i).getCell(3).setCellValue(data.getValidOrderCount());
                sheet.getRow(7+i).getCell(4).setCellValue(data.getOrderCompletionRate());
                sheet.getRow(7+i).getCell(5).setCellValue(data.getUnitPrice());
                sheet.getRow(7+i).getCell(6).setCellValue(data.getNewUsers());
            }

            //下载
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭资源
            out.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获得日期列表
     * @param begin
     * @param end
     * @return
     */
    private List<LocalDate> getDateList(LocalDate begin, LocalDate end){
        List<LocalDate> list = new ArrayList<>();
        while (!begin.equals(end)) {
            list.add(begin);//添加日期
            begin = begin.plusDays(1);
        }
        //添加最后一天
        list.add(begin);
        return list;
    }
}
